package com.sys.tool;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2009-10-14
 * Time: 19:33:33
 * To change this template use File | Settings | File Templates.
 */
public class StringTool {

    private Pattern p;
    private Matcher m;

    private String body = null;

    /**
     * 设置正则表达式
     *
     * @param regex
     */
    public void setPattern(String regex) {
        p = Pattern.compile(regex);
        if (body != null && body.length() > 0) {
            m = p.matcher(body);
        }
    }

    public void setMatcher(String str) {
        this.body = str;
        if (p == null) {
            p = Pattern.compile("");
        }
        m = p.matcher(str);
    }


    /**
     * 得到匹配数量
     *
     * @return
     */
    public int getFindCount() {
        int count = 0;
        while (m.find()) {
            count++;
        }
        m.reset();
        return count;
    }

    public boolean isFind() {
        boolean b = m.find();
        m.reset();
        return b;
    }


    /**
     * 获得匹配结果
     *
     * @return
     */
    public String getValue(int group) {
        String value = null;
        if (m.find()) {
            try {
                value = m.group(group);
            } catch (Exception e) {
                value = "";
            }
        }
        m.reset();
        return value;
    }

    /**
     * 获得匹配结果集
     *
     * @return
     */
    public String[] getValues(int group) {
        List list = new ArrayList();
        m.reset();
        while (m.find()) {
            list.add(m.group(group));
        }
        String[] strs = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != null) {
                strs[i] = list.get(i).toString();
            } else {
                strs[i] = "";
            }
        }
        return strs;
    }


    /**
     * 将整个匹配结果集替换成制定字符
     *
     * @param value
     */
    public String replace(String value) {
        if (m.find()) {
            String r = this.m.replaceAll(value);
            m.reset();
            return r;
        }
        m.reset();
        return null;
    }

    public void main(String[] args) {

        /*StringTool.setPattern("ab");
        StringTool.setMatcher("abacbabcabc");
        System.out.println(StringTool.getFindCount());
        System.out.println(StringTool.getValue());

        for (String str : getValues()) {
            System.out.println(str);
        }*/
    }

}
